# -*- coding: utf-8 -*-

# import zjl_util
import sys
import getopt
import re
import urllib.parse
import wget
import requests
import time
import os


FILE_URL_PAT = 'href="(.*?.mp3)"'
# 刷新已下载大小时间间隔 单位：秒
INTERVAL = 1


def down(page_url, dir_path):
    # doc = zjl_util.get_doc(page_url, 4)
    doc = requests.get(page_url).text
    r = re.compile(FILE_URL_PAT).findall(doc)
    print('可下载文件：')
    for i in range(0, len(r)):
        print(i, r[i])
    offset = input('从第几集开始？')
    end = input('到第几集结束？')
    for i in range(offset, end):
        if i >= len(r):
            break
        file_url = page_url[0: page_url.rfind('/') + 1] + r[i]
        file_url = urllib.parse.unquote(file_url)
        file_name = r[i][str(r[i]).rfind('/') + 1:]
        file_name = urllib.parse.unquote(file_name)
        print('downloading ', file_name, file_url)
        file_path = dir_path + '/' + file_name
        # wget.download(file_url, file_path)
        for j in range(0, 10):
            try:
                download(file_url, file_path)
                break
            except Exception as e:
                print(e)


def download(down_url, file_path, header={
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
    "Accept-Language": "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2",
    "Accept-Encoding": "gzip, deflate, br",
    "Connection": "keep-alive",
    "Upgrade-Insecure-Requests": "1"
}):
    """下载文件并显示过程
        :param down_url: 资源地址
        :param file_path: 保存的文件路径
        :param header: 下载请求的header
        """
    t1 = time.time()
    with open(file_path, 'wb') as f:
        down_data_count = 0
        speed_count = 0
        chunk_size = 1024
        m = 1024 * 1024
        k = 1024
        size_str = ''
        with requests.get(down_url, stream=True, headers=header, timeout=20) as r:
            for chunk in r.iter_content(chunk_size):
                data_length = len(chunk)
                down_data_count += data_length
                speed_count += data_length
                f.write(chunk)

                t2 = time.time()
                if t2 - t1 > INTERVAL:
                    size_str = str(down_data_count)
                    if down_data_count > m:
                        size_str = str(down_data_count / m) + "M"
                    elif down_data_count > k:
                        size_str = str(down_data_count / k) + "K"

                    speed_str = str(speed_count)
                    if speed_count > m:
                        speed_str = str(speed_count / m) + "M"
                    elif speed_count > k:
                        speed_str = str(speed_count / k) + "K"
                    # print("                                     \t\t")
                    print(size_str + "\t" + speed_str + "/s")
                    t1 = t2
                    speed_count = 0
        print(file_path + '\t\t' + size_str)


def main():
    page_url = 'http://49.51.138.143/voice/%E8%BA%AB%E5%A4%84%E4%B8%9C%E4%BA%AC%E7%9A%84%E6%88%91%E5%8F%AA%E6%83%B3%E5%92%B8%E9%B1%BC/'
    dir_path = 'd:/test/'

    opts, args = getopt.getopt(sys.argv[1:], "hu:d:H:o:")
    for o, a in opts:
        if o == '-h':
            print("python3 down_poxiao.py -u " + page_url + " -d " + dir_path)
            exit()
        if o == '-u':
            page_url = a
        if o == '-d':
            dir_path = a
    print('页面地址：' + page_url)
    print('保存路径：' + dir_path)
    down(page_url, dir_path)


if __name__ == "__main__":
    main()